package top.kaoshanji.p1ch02d;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

/**
 * 代码清单 p1ch02d-07：MethodHandles#foldArguments的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/3 18:38
 */
public class MethodHandlesExample07 {

    private static final Logger logger = LogManager.getLogger(MethodHandlesExample07.class);

    public static void main(String[] args) throws Throwable {
        logger.info("...代码清单 p1ch02d-07：MethodHandles#foldArguments的使用示例...");

        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodType typeCombiner = MethodType.methodType(int.class, int.class, int.class);
        MethodHandle mhCombiner = lookup.findStatic(Math.class, "max", typeCombiner);

        MethodType typeTarget = MethodType.methodType(int.class, int.class, int.class, int.class);
        MethodHandle hmTarget = lookup.findStatic(MethodHandlesExample07.class, "targetMethod", typeTarget);
        MethodHandle mhResult = MethodHandles.foldArguments(hmTarget, mhCombiner);

        int value = (int)mhResult.invoke(3, 4);
        System.out.println(value);

    }

    public static int targetMethod(int arg1, int arg2, int arg3) {
        return arg1;
    }

}
